package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.admin.dtos.UserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-11-26
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    /**
     * 管理员登录
     * @param dto 用户名， 密码
     * @return 成功返回登录和令牌等信息
     */
    @Override
    public ResponseResult login(UserDto dto) {
        if (StringUtils.isEmpty(dto.getName()) && StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_ADMIN_DATA_NOT_EXIST);
        }
        AdUser adUser = lambdaQuery().eq(AdUser::getName, dto.getName()).select().one();
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_ADMIN_DATA_NOT_EXIST);
        }
        String salt = adUser.getSalt();
        String inputPs = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        if (!inputPs.equals(adUser.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_ADMIN_DATA_NOT_EXIST);
        }
        adUser.setPassword("");
        adUser.setSalt("");
        Map<String, Object> map = new HashMap<>();
        map.put("user", adUser);
        map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
        return ResponseResult.okResult(map);
    }
}
